package com.shop.servlet.cart;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shop.cart.Cart;
import com.shop.entity.Product;
import com.shop.service.ProductService;

/**
 * Servlet implementation class CartindexServlet
 */
@WebServlet("/Cartindex")
public class CartindexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartindexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String msg = "";
		int id=Integer.parseInt(request.getParameter("productId"));
		ProductService ps=new ProductService();
		Product p=ps.findProductById(id);
		HttpSession session=request.getSession();
		Cart c=(Cart)session.getAttribute("cart");
		if(c==null){
			c=new Cart();
		}
		c.addCartItem(p);
		if (id > 0) {
			msg = "添加成功,商品在购物车等你！";
			request.setAttribute("msg", msg);
			session.setAttribute("cart", c);
			request.getRequestDispatcher("productIndex").forward(request, response);
		} else {
			msg = "添加失败";
			request.setAttribute("msg", msg);
			session.setAttribute("cart", c);
			request.getRequestDispatcher("productIndex").forward(request, response);

		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
